﻿param($selectedWebApplication = $null, $features = @{applicationFiles=$true;})

trap [Exception]
{
	echo ""
	echo "An unhandled error has occured:"
	echo $_.Exception
	echo "When executing"
	echo $_.InvocationInfo.PositionMessage
	echo ""	$inTransaction = Get-EPiIsBulkInstalling

	$inTransaction = Get-EPiIsBulkInstalling

	if($inTransaction -eq $true)
	{
		Rollback-EPiBulkInstall
	}	
	
	break
}

$VerbosePreference = "Continue"
$ErrorActionPreference = "Continue"
$Product = "CMS"

# Load the EPiServer Common snapin if required
$snapIn = Get-PSSnapin -Name EPiServer.Install.Common.1 -ErrorAction SilentlyContinue
if ($snapIn -eq $null)
{
	Add-PSSnapin EPiServer.Install.Common.1
}

# Get the version location path of EPiServer in order to find resources
$CurrentDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$epiVersion = Get-EPiVersion -MapPath $CurrentDir

# Load the EPiServer CMS snapin if required
$snapIn = Get-PSSnapin -Name EPiServer.Install.CMS.$epiVersion -ErrorAction SilentlyContinue
if ($snapIn -eq $null)
{
	Add-PSSnapin EPiServer.Install.CMS.$epiVersion
}

$proceedWithInstall = $true

# The wizard is used for progress messages so load it even if we don't need to display it
$wizard = New-EPiCMSWizard "InstallModuleWizard" ($MyInvocation.MyCommand.Path)

$wizard.Features = $features

$epiProductInfo = Get-EPiProductInformation -ProductName $Product -ProductVersion $epiVersion
if (!$epiProductInfo.IsInstalled)
{
	throw(New-Object ApplicationException($wizard.Resources.GetString("ErrorInstallationDirectoryNotFound")))
}
$sourceTemplateFolder = [System.IO.Path]::Combine($epiProductInfo.InstallationPath, "Install\Modules\ETF")

if ($selectedWebApplication -eq $null)
{	
	$wizard.CMSVersions = Get-CompatibleProductVersions -ModuleScriptPath $MyInvocation.MyCommand.Path
	$wizard.ValidateDatabaseConnection = $true
	$wizard.Title = "Add ETF to EPiServer website"
	$proceedWithInstall = $wizard.Show()
	
	if ($proceedWithInstall)
	{
		$selectedWebApplication = $wizard.SelectedApplication		
	}
}

if ($proceedWithInstall)
{
	# Read back features
	$features = $wizard.Features
	
	$inTransaction = Get-EPiIsBulkInstalling

	if($inTransaction -eq $false)
	{
		Begin-EPiBulkInstall -SelectedSite $selectedWebApplication -RunDistributedTransaction -StartMSDTC
	}

	Set-EPiProgressStatus -status "Adding ETF to website..."

    if ($features.applicationFiles)
    {
        Set-EPiProgressStatus -status "Verifying Page Type Builder binary is present..."
        
        $ptbAssemblyPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "bin\PageTypeBuilder.dll")
    
        if(!(Test-Path $ptbAssemblyPath))
        {
            throw("Page Type Builder is required, ensure PageTypeBuilder.dll exists in the 'bin' folder.")
        }
    
        Set-EPiProgressStatus -status "Copying ETF binary to 'bin' folder..."
        
        $siteBinFolder = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "bin")
        
        Copy-EPiFiles -SourceDirectoryPath $sourceTemplateFolder -DestinationDirectoryPath $siteBinFolder -Exclude "*.ps1,*.metadata,*.xmlupdate,*.txt" -Recursive -ProgressPercent 60   	
    }
    
    if ($features.updateConfiguration)
    {
        Set-EPiProgressStatus -status "Updating web.config..."
   
    	$modificationFile = [System.IO.Path]::Combine($sourceTemplateFolder, "ETF.xmlupdate")
    	$targetWebConfigPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "web.config")
        
        Update-EPiXmlFile -ModificationFilePath $modificationFile -TargetFilePath $targetWebConfigPath
    }
    
    Add-EPiProgressPercentComplete -percent 40
    
    if ($features.useBritishFlag)
    {
        Set-EPiProgressStatus -status "Updating web.config to use British flag for 'en' language branch..."
    	
    	$modificationFile = [System.IO.Path]::Combine($sourceTemplateFolder, "ETF.BritishFlagForEnLanguageBranch.xmlupdate")
    	$targetWebConfigPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "web.config")
        
        Update-EPiXmlFile -ModificationFilePath $modificationFile -TargetFilePath $targetWebConfigPath
    }
    
    Add-EPiProgressPercentComplete -percent 30
    
    if ($features.addLoginLogo)
    {
    	Set-EPiProgressStatus -status "Updating web.config to display Ted & Gustaf logo on EPiServer login page..."
        
    	$modificationFile = [System.IO.Path]::Combine($sourceTemplateFolder, "ETF.TedGustafLoginLogo.xmlupdate")
    	$targetWebConfigPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "web.config")
        
        Update-EPiXmlFile -ModificationFilePath $modificationFile -TargetFilePath $targetWebConfigPath
    }
	
	Add-EPiProgressPercentComplete -percent 25

	if($inTransaction -eq $false)
	{
		Commit-EPiBulkInstall
		Add-EPiProgressPercentComplete -percent 5
	}

	Set-EPiProgressStatus -status "ETF installer completed."
}